<template>
  <view class="page-container">
    <!-- 搜索和筛选 -->
    <view class="filter-section">
      <view class="search-wrapper">
        <u-search
          v-model="searchForm.keyword"
          placeholder="搜索拼班名称或班级号"
          :clearabled="true"
          :showAction="false"
          @search="onSearch"
        />
      </view>
      
      <!-- 状态筛选 -->
      <view class="status-filter">
        <scroll-view class="status-scroll" scroll-x="true" :show-scrollbar="false">
          <view class="status-tabs">
            <view 
              class="status-tab" 
              :class="{ active: currentStatus === 'all' }"
              @click="switchStatus('all')"
            >
              全部
            </view>
            <view 
              class="status-tab" 
              :class="{ active: currentStatus === 'pending' }"
              @click="switchStatus('pending')"
            >
              拼班中
            </view>
            <view 
              class="status-tab" 
              :class="{ active: currentStatus === 'formed' }"
              @click="switchStatus('formed')"
            >
              已成班
            </view>
            <view 
              class="status-tab" 
              :class="{ active: currentStatus === 'failed' }"
              @click="switchStatus('failed')"
            >
              已失败
            </view>
            <view 
              class="status-tab" 
              :class="{ active: currentStatus === 'completed' }"
              @click="switchStatus('completed')"
            >
              已完成
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 拼班列表 -->
    <scroll-view class="list-container" scroll-y="true" @scrolltolower="loadMore">
      <view class="class-list">
        <view class="class-card" v-for="(item, index) in classList" :key="item.id">
          <!-- 状态标签 -->
          <view class="status-badge" :class="getStatusClass(item.group_status)">
            {{ getStatusText(item.group_status) }}
          </view>
          
          <!-- 班级信息 -->
          <view class="card-header">
            <view class="class-title">{{ item.class_name }}</view>
            <view class="class-sn">班级号：{{ item.class_sn }}</view>
          </view>
          
          <view class="card-content">
            <!-- 课程信息 -->
            <view class="course-info">
              <view class="course-title">{{ item.course_title }}</view>
              <view class="course-meta">
                <text class="course-type">{{ item.course_type }}</text>
                <text class="age-range">{{ item.age_range }}</text>
              </view>
            </view>
            
            <!-- 时间地点 -->
            <view class="schedule-info">
              <view class="info-row">
                <u-icon size="20" name="clock" color="#666" />
                <text>{{ item.start_time }}</text>
              </view>
              <view class="info-row">
                <u-icon size="20" name="map" color="#666" />
                <text>{{ item.location_name }}</text>
              </view>
              <view class="info-row" v-if="item.deadline_time">
                <u-icon size="20" name="calendar" color="#666" />
                <text>截止：{{ item.deadline_time }}</text>
              </view>
            </view>
            
            <!-- 报名统计 -->
            <view class="enrollment-stats">
              <view class="stats-item">
                <text class="stats-label">已报名：</text>
                <text class="stats-value">{{ item.current_real_users }}人</text>
              </view>
              <view class="stats-item">
                <text class="stats-label">成班要求：</text>
                <text class="stats-value">{{ item.min_users }}-{{ item.max_users }}人</text>
              </view>
              <view class="stats-item" v-if="item.current_boutique_users > 0">
                <text class="stats-label">精品班：</text>
                <text class="stats-value">{{ item.current_boutique_users }}人</text>
              </view>
            </view>
            
            <!-- 价格信息 -->
            <view class="price-info">
              <view class="price-item">
                <text class="price-label">普通班：</text>
                <text class="price-value">￥{{ item.normal_price }}</text>
              </view>
              <view class="price-item" v-if="item.boutique_price > 0">
                <text class="price-label">精品班：</text>
                <text class="price-value">￥{{ item.boutique_price }}</text>
              </view>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="card-actions">
            <view class="btn detail-btn" @click="viewDetail(item)">详情</view>
            <view class="btn students-btn" @click="manageStudents(item)">学员管理</view>
            <view 
              class="btn refund-btn" 
              v-if="canRefundClass(item)"
              @click="showRefundOptions(item)"
            >
              退班管理
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="loading">
        <u-loading size="20" color="#999"></u-loading>
        <text class="load-text">加载中...</text>
      </view>
      <view class="no-more" v-if="noMore && classList.length > 0">
        <text>没有更多数据了</text>
      </view>
      <view class="empty-state" v-if="classList.length === 0 && !loading">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image" />
        <text class="empty-text">暂无拼班数据</text>
      </view>
    </scroll-view>
    
    <!-- 退班管理弹窗 -->
    <u-popup v-model="showRefundModal" mode="center" width="600rpx" border-radius="16">
      <view class="refund-modal">
        <view class="modal-header">
          <text class="modal-title">退班管理</text>
          <u-icon name="close" size="32" color="#999" @click="showRefundModal = false"></u-icon>
        </view>
        <view class="modal-content">
          <view class="class-info">
            <text class="class-name">{{ selectedClass.class_name }}</text>
            <text class="class-sn">班级号：{{ selectedClass.class_sn }}</text>
          </view>
          
          <!-- 学员列表 -->
          <view class="student-list" v-if="classStudents.length > 0">
            <view class="list-title">选择要退班的学员：</view>
            <view 
              class="student-item" 
              v-for="student in classStudents" 
              :key="student.id"
              @click="toggleStudentSelection(student)"
            >
              <view class="student-info">
                <image :src="student.avatar_url || '/static/images/default-avatar.png'" class="student-avatar" />
                <view class="student-details">
                  <text class="student-name">{{ student.name }}</text>
                  <text class="student-meta">年龄：{{ student.age }}岁</text>
                </view>
              </view>
              <view class="selection-status">
                <u-icon 
                  :name="student.selected ? 'checkmark-circle' : 'radio-button-off'" 
                  :color="student.selected ? '#0dc160' : '#ccc'" 
                  size="32"
                />
              </view>
            </view>
          </view>
          
          <!-- 退班原因 -->
          <view class="refund-reason">
            <view class="reason-title">退班原因（可选）：</view>
            <u-input 
              v-model="refundForm.reason" 
              type="textarea" 
              placeholder="请输入退班原因"
              :maxlength="200"
              height="120"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="btn cancel-btn" @click="showRefundModal = false">取消</view>
          <view 
            class="btn confirm-btn" 
            :class="{ disabled: selectedStudents.length === 0 }"
            @click="confirmRefund"
          >
            确认退班
          </view>
        </view>
      </view>
    </u-popup>
    
    <!-- 确认退班弹窗 -->
    <u-popup v-model="showConfirmModal" mode="center" width="500rpx" border-radius="16">
      <view class="confirm-modal">
        <view class="confirm-icon">
          <u-icon name="warning-circle" size="64" color="#ff6b35" />
        </view>
        <view class="confirm-title">确认退班</view>
        <view class="confirm-content">
          <text>确定要为 {{ selectedStudents.length }} 名学员办理退班吗？</text>
          <text class="refund-notice">退班后将按规则计算退款金额</text>
        </view>
        <view class="confirm-actions">
          <view class="btn cancel-btn" @click="showConfirmModal = false">取消</view>
          <view class="btn confirm-btn" @click="executeRefund">确认</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getGroupClassList, getClassStudents, refundClass } from '@/api/group_class';

export default {
  data() {
    return {
      searchForm: {
        keyword: ''
      },
      currentStatus: 'all',
      classList: [],
      loading: false,
      noMore: false,
      page: 1,
      pageSize: 10,
      
      // 退班相关
      showRefundModal: false,
      showConfirmModal: false,
      selectedClass: {},
      classStudents: [],
      selectedStudents: [],
      refundForm: {
        reason: ''
      }
    };
  },
  
  computed: {
    // 计算属性
  },
  
  onLoad() {
    this.loadClassList(true);
  },
  
  onPullDownRefresh() {
    this.loadClassList(true).then(() => {
      uni.stopPullDownRefresh();
    });
  },
  
  methods: {
    // 加载拼班列表
    async loadClassList(refresh = false) {
      if (refresh) {
        this.page = 1;
        this.classList = [];
        this.noMore = false;
      }
      
      if (this.loading || this.noMore) return;
      
      this.loading = true;
      
      try {
        const params = {
          page: this.page,
          size: this.pageSize,
          keyword: this.searchForm.keyword,
          status: this.currentStatus !== 'all' ? this.currentStatus : ''
        };
        
        const res = await getGroupClassList(params);
        
        if (res && res.list) {
          if (refresh) {
            this.classList = res.list;
          } else {
            this.classList = [...this.classList, ...res.list];
          }
          
          if (res.list.length < this.pageSize) {
            this.noMore = true;
          } else {
            this.page++;
          }
        }
      } catch (error) {
        console.error('加载拼班列表失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 状态切换
    switchStatus(status) {
      this.currentStatus = status;
      this.loadClassList(true);
    },
    
    // 搜索
    onSearch() {
      this.loadClassList(true);
    },
    
    // 加载更多
    loadMore() {
      this.loadClassList(false);
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/class_manage/group_class_detail?id=${item.id}`
      });
    },
    
    // 学员管理
    manageStudents(item) {
      uni.navigateTo({
        url: `/pages/class_manage/student_management?classId=${item.id}`
      });
    },
    
    // 显示退班选项
    async showRefundOptions(item) {
      this.selectedClass = item;
      
      try {
        // 获取班级学员列表
        const res = await getClassStudents({ class_id: item.id });
        if (res && res.students) {
          this.classStudents = res.students.map(student => ({
            ...student,
            selected: false
          }));
          this.selectedStudents = [];
          this.refundForm.reason = '';
          this.showRefundModal = true;
        }
      } catch (error) {
        console.error('获取学员列表失败:', error);
        uni.showToast({
          title: '获取学员列表失败',
          icon: 'none'
        });
      }
    },
    
    // 切换学员选择状态
    toggleStudentSelection(student) {
      student.selected = !student.selected;
      this.selectedStudents = this.classStudents.filter(s => s.selected);
    },
    
    // 确认退班
    confirmRefund() {
      if (this.selectedStudents.length === 0) {
        uni.showToast({
          title: '请选择要退班的学员',
          icon: 'none'
        });
        return;
      }
      
      this.showRefundModal = false;
      this.showConfirmModal = true;
    },
    
    // 执行退班
    async executeRefund() {
      this.showConfirmModal = false;
      
      try {
        uni.showLoading({ title: '处理中...' });
        
        // 批量处理退班
        const refundPromises = this.selectedStudents.map(student => 
          refundClass({
            class_id: this.selectedClass.id,
            student_id: student.id,
            reason: this.refundForm.reason
          })
        );
        
        await Promise.all(refundPromises);
        
        uni.hideLoading();
        uni.showToast({
          title: '退班成功',
          icon: 'success'
        });
        
        // 刷新列表
        this.loadClassList(true);
        
      } catch (error) {
        uni.hideLoading();
        console.error('退班失败:', error);
        uni.showToast({
          title: '退班失败',
          icon: 'none'
        });
      }
    },
    
    // 判断是否可以退班
    canRefundClass(item) {
      // 只有进行中和已成班的拼班才能退班
      return [1, 2, 3, 8].includes(item.group_status);
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        0: 'status-scheduling',
        1: 'status-pending',
        2: 'status-formed',
        3: 'status-boutique',
        8: 'status-boutique-formed',
        4: 'status-failed',
        5: 'status-completed',
        6: 'status-cancelled'
      };
      return statusMap[status] || 'status-unknown';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '排课中',
        1: '拼班中',
        2: '待开课',
        3: '精品班拼班中',
        8: '精品班待开课',
        4: '已失败',
        5: '已完成',
        6: '已取消'
      };
      return statusMap[status] || '未知状态';
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .filter-section {
    background: #fff;
    padding: 24rpx;
    border-bottom: 1px solid #eee;
    
    .search-wrapper {
      margin-bottom: 24rpx;
    }
    
    .status-filter {
      .status-scroll {
        white-space: nowrap;
      }
      
      .status-tabs {
        display: flex;
        gap: 24rpx;
        
        .status-tab {
          padding: 16rpx 32rpx;
          border-radius: 32rpx;
          font-size: 28rpx;
          color: #666;
          background: #f8f9fa;
          white-space: nowrap;
          transition: all 0.3s ease;
          
          &.active {
            color: #fff;
            background: linear-gradient(135deg, #0dc160, #13ce66);
          }
        }
      }
    }
  }
  
  .list-container {
    flex: 1;
    height: calc(100vh - 200rpx);
    
    .class-list {
      padding: 24rpx;
      
      .class-card {
        background: #fff;
        border-radius: 16rpx;
        padding: 32rpx;
        margin-bottom: 24rpx;
        position: relative;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
        
        .status-badge {
          position: absolute;
          top: 0;
          right: 0;
          padding: 8rpx 20rpx;
          border-radius: 0 16rpx 0 16rpx;
          font-size: 24rpx;
          font-weight: bold;
          color: #fff;
          
          &.status-scheduling {
            background: #f36806;
          }
          &.status-pending {
            background: #1890ff;
          }
          &.status-formed {
            background: #52c41a;
          }
          &.status-boutique {
            background: #722ed1;
          }
          &.status-boutique-formed {
            background: #13c2c2;
          }
          &.status-failed {
            background: #f5222d;
          }
          &.status-completed {
            background: #8c8c8c;
          }
          &.status-cancelled {
            background: #bfbfbf;
          }
        }
        
        .card-header {
          margin-bottom: 24rpx;
          
          .class-title {
            font-size: 36rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 8rpx;
          }
          
          .class-sn {
            font-size: 24rpx;
            color: #999;
          }
        }
        
        .card-content {
          .course-info {
            margin-bottom: 24rpx;
            
            .course-title {
              font-size: 32rpx;
              color: #333;
              margin-bottom: 8rpx;
            }
            
            .course-meta {
              display: flex;
              gap: 16rpx;
              
              .course-type, .age-range {
                font-size: 24rpx;
                color: #666;
                padding: 4rpx 12rpx;
                background: #f0f0f0;
                border-radius: 8rpx;
              }
            }
          }
          
          .schedule-info {
            margin-bottom: 24rpx;
            
            .info-row {
              display: flex;
              align-items: center;
              margin-bottom: 12rpx;
              font-size: 28rpx;
              color: #666;
              
              .u-icon {
                margin-right: 8rpx;
              }
            }
          }
          
          .enrollment-stats {
            display: flex;
            flex-wrap: wrap;
            gap: 24rpx;
            margin-bottom: 24rpx;
            
            .stats-item {
              display: flex;
              align-items: center;
              
              .stats-label {
                font-size: 24rpx;
                color: #666;
              }
              
              .stats-value {
                font-size: 24rpx;
                color: #333;
                font-weight: bold;
              }
            }
          }
          
          .price-info {
            display: flex;
            gap: 32rpx;
            margin-bottom: 24rpx;
            
            .price-item {
              display: flex;
              align-items: center;
              
              .price-label {
                font-size: 24rpx;
                color: #666;
              }
              
              .price-value {
                font-size: 28rpx;
                color: #f36806;
                font-weight: bold;
              }
            }
          }
        }
        
        .card-actions {
          display: flex;
          gap: 16rpx;
          justify-content: flex-end;
          
          .btn {
            padding: 16rpx 32rpx;
            border-radius: 8rpx;
            font-size: 24rpx;
            text-align: center;
            
            &.detail-btn {
              background: #f0f0f0;
              color: #333;
            }
            
            &.students-btn {
              background: #e6f7ff;
              color: #1890ff;
            }
            
            &.refund-btn {
              background: #fff2e8;
              color: #fa8c16;
            }
          }
        }
      }
    }
    
    .load-more, .no-more {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 32rpx;
      color: #999;
      font-size: 24rpx;
      
      .load-text {
        margin-left: 16rpx;
      }
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 120rpx 32rpx;
      
      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 32rpx;
      }
      
      .empty-text {
        color: #999;
        font-size: 28rpx;
      }
    }
  }
}

// 弹窗样式
.refund-modal, .confirm-modal {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1px solid #eee;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 32rpx;
    max-height: 600rpx;
    overflow-y: auto;
    
    .class-info {
      margin-bottom: 32rpx;
      
      .class-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .class-sn {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .student-list {
      margin-bottom: 32rpx;
      
      .list-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
      }
      
      .student-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16rpx;
        margin-bottom: 12rpx;
        background: #f8f9fa;
        border-radius: 8rpx;
        
        .student-info {
          display: flex;
          align-items: center;
          
          .student-avatar {
            width: 64rpx;
            height: 64rpx;
            border-radius: 50%;
            margin-right: 16rpx;
          }
          
          .student-details {
            .student-name {
              font-size: 28rpx;
              color: #333;
              display: block;
              margin-bottom: 4rpx;
            }
            
            .student-meta {
              font-size: 24rpx;
              color: #666;
            }
          }
        }
      }
    }
    
    .refund-reason {
      .reason-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    gap: 16rpx;
    padding: 32rpx;
    border-top: 1px solid #eee;
    
    .btn {
      flex: 1;
      padding: 20rpx;
      border-radius: 8rpx;
      text-align: center;
      font-size: 28rpx;
      
      &.cancel-btn {
        background: #f0f0f0;
        color: #333;
      }
      
      &.confirm-btn {
        background: #1890ff;
        color: #fff;
        
        &.disabled {
          background: #ccc;
          color: #999;
        }
      }
    }
  }
}

.confirm-modal {
  padding: 48rpx 32rpx;
  text-align: center;
  
  .confirm-icon {
    margin-bottom: 24rpx;
  }
  
  .confirm-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .confirm-content {
    margin-bottom: 48rpx;
    
    text {
      display: block;
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      margin-bottom: 8rpx;
    }
    
    .refund-notice {
      color: #fa8c16;
      font-size: 24rpx;
    }
  }
  
  .confirm-actions {
    display: flex;
    gap: 16rpx;
    
    .btn {
      flex: 1;
      padding: 20rpx;
      border-radius: 8rpx;
      text-align: center;
      font-size: 28rpx;
      
      &.cancel-btn {
        background: #f0f0f0;
        color: #333;
      }
      
      &.confirm-btn {
        background: #f5222d;
        color: #fff;
      }
    }
  }
}
</style> 